import "../../lib/ramda.js"
import utils from "../../lib/utils.js"
import ux from "./ux.js"
import game from "./game.js"

const Consts = {
    DEV_VERSION: 20240212,
    FPS:20,
}

const Raii = {
    _raiis:[],
    add(f){
        Raii._raiis.push(f)
        return Raii
    },
    raii(){
        Raii._raiis.forEach(R.applyTo(undefined))
        Raii._raiis = undefined
        return Raii
    }
}
window.onbeforeunload = function(){
    Raii.raii()
    console.log("(raii)")
}

const AiManager = (()=>{
    const me = {}
    const _observers = []
    function make(){
        const worker = new Worker("./ai-engine.js", {type: "module"})
        worker.onmessage = (e)=>{
            const msg = e.data
            _observers.forEach(R.applyTo(msg))
        }
        worker.onerror = (e)=>{
            console.log(`AI-Error(${e.filename}[${e.lineno}]): ${e.message}`, e)
        }
        return worker
    }
    let _worker = make()
    me.listen = (f)=>{
        _observers.push(f)
        return me
    }
    me.send  = (msg)=>{
        const text = msg.toString()
        _worker.postMessage(text)
        return me
    }
    me.restart = ()=>{
        _worker.postMessage("ai.end")
        _worker.terminate()
        _worker = make()
        return me
    }
    return me
})()

const DEFAULT_REDIS = {
    "[lianstar]!dev": Consts.DEV_VERSION,
    // 对局设置
    "[lianstar]rule": "无禁手",
    "[lianstar]maxtime-total": 600,
    "[lianstar]maxtime-step": 60,
    // AI设置
    "[lianstar]ai.uct-max-time": 65536,
    "[lianstar]ai.vc-max-depth": 8,
    "[lianstar]ai.search-depth": 6,
}
utils.redis.init()
utils.redis.Event.on_key_notfound = (k)=>{
    return DEFAULT_REDIS[k]
}

const kvs = {
    _f(t, k, v=undefined) {
        const k_fix = `[lianstar]${k}`
        if (R.isNil(v)) {
            return t[k_fix]
        } else {
            t[k_fix] = v
        }
    },
    text(k, v=undefined){return kvs._f(utils.redis.text, k, v)},
    number(k, v=undefined){return kvs._f(utils.redis.number, k, v)},
    bool(k, v=undefined){return kvs._f(utils.redis.bool, k, v)},
}

if (kvs.number("!dev") != Consts.DEV_VERSION){
    utils.redis.sets(DEFAULT_REDIS)
}
game.init()
ux.init(AiManager, kvs)
utils.clock.frame_watch(ux.frame).frame_watch(game.PK.timer_frame).start(Consts.FPS)
Raii.add(utils.clock.stop)
